package com.gh.lucene.util.index;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;

import com.gh.lucene.util.UserData;
import com.gh.lucene.util.store.DocumentException;
import com.gh.lucene.util.store.SimpleUserDocumentFactory;
import com.gh.lucene.util.store.UserDocument;
import com.gh.lucene.util.store.UserDocumentFactory;

/**
 * 此类的具体索引的抽象类，他抽象出一个 map(UserData) 方法
 * 
 * @author bastengao
 * 
 */
public abstract class Indexer implements Indexable {
	private UserDocumentFactory userDocumentFactory = new SimpleUserDocumentFactory();
	private IndexWriter indexWriter = null;

	public Indexer(IndexWriter indexWriter) {
		super();
		if (indexWriter == null) {
			throw new IllegalArgumentException("index writer is null");
		}
		this.indexWriter = indexWriter;
	}

	@Override
	public void index(UserData userData) throws IndexException {
		UserDocument document = map(userData);
		try {
			indexWriter.addDocument(document.getDocument());
		} catch (CorruptIndexException e) {
			e.printStackTrace();
			throw new IndexException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new IndexException(e);
		} catch (DocumentException e) {
			e.printStackTrace();
			throw new IndexException(e);
		}
	}

	public UserDocument assemble(UserData userData, Document document) {
		return userDocumentFactory.assemble(userData, document);
	}

	abstract protected UserDocument map(UserData userData);

	public void setUserDocumentFactory(UserDocumentFactory factory) {
		this.userDocumentFactory = factory;
	}

	@Override
	public void close() throws IndexException {
		try {
			indexWriter.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
			throw new IndexException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new IndexException(e);
		}
	}

	@Override
	public void commit() {

	}
}
